package com.cbg.discount.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cbg.base.constant.Constant;
import com.cbg.base.core.SuperServiceImpl;
import com.cbg.discount.entity.Discount;
import com.cbg.discount.entity.DiscountRecord;
import com.cbg.discount.mapper.DiscountRecordMapper;
import com.cbg.discount.service.IDiscountRecordService;
import com.cbg.discount.service.IDiscountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.sql.Date;

/**
 * 获取优惠券记录服务实现类
 */
@Service
public class DiscountRecordServiceImpl extends SuperServiceImpl<DiscountRecordMapper, DiscountRecord> implements IDiscountRecordService {
    //首次登录渠道id
    @Value("${discount-channel.first-login-channelId}")
    private String channelId;

    @Autowired
    IDiscountService discountService;

    /**
     * 首次登录注册   送优惠券
     */
    @Override
    public void firstLogin(String userId) {
        //获取首次优惠券
        Discount discount = discountService.getOne(new LambdaQueryWrapper<Discount>().eq(Discount::getType, Constant.FIRST_DISCOUNT_TYPE));
        if (ObjectUtil.isNotNull(discount)) {
            Date date = discount.getValidDays() > 0 ? getDateAdd(discount.getValidDays()) : discount.getValidDate();
            new DiscountRecord()
                    .setUserId(userId)
                    .setDiscountId(discount.getId())
                    .setAmount(1)
                    .setChannelId(channelId)
                    .setArriveDate(date)
                    .insert();
        }
    }


    /**
     * 发送优惠券
     *
     * @param userId
     * @param discountId
     * @param channelId
     * @param amount
     */
    @Override
    public void send(String userId, String discountId, String channelId, int amount) {
        Discount discount = discountService.getById(new LambdaQueryWrapper<Discount>().eq(Discount::getId, discountId));
        if (ObjectUtil.isNotNull(discount)) {
            Date date = discount.getValidDays() > 0 ? getDateAdd(discount.getValidDays()) : discount.getValidDate();
            new DiscountRecord()
                    .setUserId(userId)
                    .setDiscountId(discountId)
                    .setAmount(amount)
                    .setChannelId(channelId)
                    .setArriveDate(date)
                    .insert();
        }
    }


    /**
     * 获取从往后的days 天的时间
     *
     * @param days
     * @return
     */
    public Date getDateAdd(int days) {
        Long time = System.currentTimeMillis();
        Date date = new Date(time+days *1000 *60);
        return date;
    }


}
